package com.zys.test;

import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

@Slf4j
public class WechatUtil {
    public static WeChatUser getUserInfo(String code) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();

        String tokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx73a67e59e6c01244&secret=70b749025f06d8551e319aa1f7c61ac7&code=" + code + "&grant_type=authorization_code";

        HttpGet httpGet = new HttpGet(tokenUrl);
        String responseResult = "";

        CloseableHttpResponse response = httpClient.execute(httpGet);
        if (response.getStatusLine().getStatusCode() == 200) {
            responseResult = EntityUtils.toString(response.getEntity(), "UTF-8");
        }
        log.info("获取accessToken返回结果：{}", responseResult);
        TokenInfo tokenInfo = JSON.parseObject(responseResult, TokenInfo.class);

        String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + tokenInfo.getAccessToken() + "&openid=" + tokenInfo.getOpenId() + "&lang=zh_CN";

        HttpGet httpGet1 = new HttpGet(userInfoUrl);

        CloseableHttpResponse response1 = httpClient.execute(httpGet1);
        if (response1.getStatusLine().getStatusCode() == 200) {
            responseResult = EntityUtils.toString(response1.getEntity(), "UTF-8");
        }
        log.info("获取用户信息返回结果：{}", responseResult);
        WeChatUser weChatUser = JSON.parseObject(responseResult, WeChatUser.class);
        return weChatUser;
    }
}
